/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.miniapp.api.miniappmemberuser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.param.MemberUserParam;
import vip.xiaonuo.facedoor.modular.memberuser.service.FacedoorMemberUserService;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.miniapp.api.miniappmemberuser.MiniProMemberUserVo;
import vip.xiaonuo.miniapp.api.miniappmemberuser.entity.MiniappMemberUser;
import vip.xiaonuo.miniapp.api.miniappmemberuser.enums.MiniappMemberUserExceptionEnum;
import vip.xiaonuo.miniapp.api.miniappmemberuser.mapper.MiniappMemberUserMapper;
import vip.xiaonuo.miniapp.api.miniappmemberuser.param.MiniappMemberUserParam;
import vip.xiaonuo.miniapp.api.miniappmemberuser.service.MiniappMemberUserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 小程序内部人员录入service接口实现类
 *
 * @author 胡鹏达
 * @date 2022-10-17 17:18:51
 */
@Service
@Slf4j
public class MiniappMemberUserServiceImpl extends ServiceImpl<MiniappMemberUserMapper, MiniappMemberUser> implements MiniappMemberUserService {

    @Resource
    private MiniappMemberUserMapper userMapper;

    @Resource
    private FacedoorMemberUserService userService;


    @Resource
    private MemberUserService memberUserService;

    @Override
    public PageResult<MiniProMemberUserVo> page(MiniappMemberUserParam miniappMemberUserParam) {
        return new PageResult<MiniProMemberUserVo>(userMapper.findPage(PageFactory.defaultPage(), miniappMemberUserParam));
    }

    @Override
    public List<MiniappMemberUser> list(MiniappMemberUserParam miniappMemberUserParam) {
        return this.list();
    }

    @Override
    public void add(MiniappMemberUserParam miniappMemberUserParam) {
        if (isExist(miniappMemberUserParam)) {
            throw new ServiceException(11, "身份证号:[" + miniappMemberUserParam.getIdCard() + "]的用户已存在");
        }

        MiniappMemberUser miniappMemberUser = new MiniappMemberUser();
        BeanUtil.copyProperties(miniappMemberUserParam, miniappMemberUser);
        this.save(miniappMemberUser);
        miniappMemberUserParam.setId(miniappMemberUser.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(MiniappMemberUserParam miniappMemberUserParam) {
        this.removeById(miniappMemberUserParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MiniappMemberUserParam miniappMemberUserParam) {
        if (StringUtils.isNoneBlank(miniappMemberUserParam.getIcCard()) && isExist(miniappMemberUserParam)) {
            throw new ServiceException(11, "身份证号:[" + miniappMemberUserParam.getIdCard() + "]的用户已存在");
        }
        MiniappMemberUser miniappMemberUser = this.queryMiniappMemberUser(miniappMemberUserParam);
        BeanUtil.copyProperties(miniappMemberUserParam, miniappMemberUser);
        this.updateById(miniappMemberUser);

        // 原始数据状态为未审核 且 提交过来的数据为审核通过
        if (miniappMemberUser.getStatus() == 1) {
            MemberUser memberUser = memberUserService.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getMiniAppMemberId, miniappMemberUserParam.getId()));
            MemberUserParam user = new MemberUserParam();
            BeanUtil.copyProperties(miniappMemberUser, user);
            user.setMiniAppMemberId(miniappMemberUserParam.getId());
            if (memberUser == null) {
                log.info("新增内部人员:{}", user);
                user.setId(null);
                userService.add(user);
            } else {
                log.info("更新内部人员:{}", user);
                user.setId(memberUser.getId());
                userService.edit(user);
            }
        }
    }

    @Override
    public MiniappMemberUser detail(MiniappMemberUserParam miniappMemberUserParam) {
        return this.queryMiniappMemberUser(miniappMemberUserParam);
    }

    /**
     * 获取小程序内部人员录入
     *
     * @author 胡鹏达
     * @date 2022-10-17 17:18:51
     */
    private MiniappMemberUser queryMiniappMemberUser(MiniappMemberUserParam miniappMemberUserParam) {
        MiniappMemberUser miniappMemberUser = this.getById(miniappMemberUserParam.getId());
        if (ObjectUtil.isNull(miniappMemberUser)) {
            throw new ServiceException(MiniappMemberUserExceptionEnum.NOT_EXIST);
        }
        return miniappMemberUser;
    }

    private boolean isExist(MiniappMemberUserParam param) {
        List<MiniappMemberUser> list = new ArrayList<>();
        if (param.getId() != null) {
            Long[] id = new Long[]{param.getId()};
            list = this.list(new LambdaQueryWrapper<MiniappMemberUser>().eq(MiniappMemberUser::getIdCard, param.getIdCard()).notIn(MiniappMemberUser::getId, id));
        } else {
            list = this.list(new LambdaQueryWrapper<MiniappMemberUser>().eq(MiniappMemberUser::getIdCard, param.getIdCard()));
        }
        return list.size() > 0;
    }
}
